package com.wukang.photovoltaicinspectionpictures.ui.adapter

import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView.Adapter
import androidx.recyclerview.widget.RecyclerView.ViewHolder
import com.wukang.photovoltaicinspectionpictures.R
import com.wukang.photovoltaicinspectionpictures.bean.TaskData
import com.wukang.photovoltaicinspectionpictures.databinding.ItemTaskListBinding
import com.wukang.photovoltaicinspectionpictures.utils.formatToDateString
import com.wukang.photovoltaicinspectionpictures.utils.onDebounceClick

/**
 * 任务列表适配器
 * @author wukang
 */
class TaskListAdapter(private val taskDataList: List<TaskData>) : Adapter<TaskListHolder>() {
    private var selectPosition: Int? = null

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): TaskListHolder {
        return TaskListHolder(ItemTaskListBinding.inflate(LayoutInflater.from(parent.context), parent, false))
    }

    override fun getItemCount(): Int {
        return taskDataList.size
    }

    override fun onBindViewHolder(holder: TaskListHolder, position: Int) {
        holder.onBindView(taskDataList[position])
        holder.itemView.setBackgroundResource(
            if (position == selectPosition) {
                R.color.item_bg_select
            } else {
                R.color.item_bg_content
            }
        )
        holder.itemView.onDebounceClick {
            selectPosition = holder.getAdapterPosition()
            notifyDataSetChanged()
        }
    }

    fun getSelectTaskData(): TaskData? = selectPosition?.let { taskDataList[it] }
}

/**
 * 任务列表视图缓存
 * @author wukang
 */
class TaskListHolder(private val binding: ItemTaskListBinding) : ViewHolder(binding.root) {
    fun onBindView(taskData: TaskData) {
        binding.tvTaskName.text = taskData.taskName
        binding.tvPowerStationName.text = taskData.powerStationName
        binding.tvPhotographLocation.text = taskData.photographLocation
        binding.tvUpdateTime.text = taskData.updateTime.formatToDateString()
        binding.tvPhotographEquipment.text = taskData.photographEquipment
        binding.tvPhotographNotes.text = taskData.photographNotes
    }
}